package com.glory.wxelectricitypda.activity;

import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.glory.wxelectricitypda.R;
import com.glory.wxelectricitypda.base.BaseDialogActivity;
import com.glory.wxelectricitypda.bean.BaseResponseBean;
import com.glory.wxelectricitypda.bean.BoxPackageTypeEntity;
import com.glory.wxelectricitypda.bean.PackBean;
import com.glory.wxelectricitypda.bean.ResponseBean;
import com.glory.wxelectricitypda.bean.ResponseQueryBean;
import com.glory.wxelectricitypda.fragment.AlreadyDoneFragment;
import com.glory.wxelectricitypda.fragment.NotDoneFragment;
import com.glory.wxelectricitypda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_TabEntity;
import com.pda.platform.ui.ui_pdaplatform.tablayout.CommonTabLayout;
import com.pda.platform.ui.ui_pdaplatform.tablayout.listener.CustomTabEntity;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PackPackageActivity extends BaseDialogActivity {


    public String packType = "SmallBoxPackageType";
    @BindView(R.id.etLotId)
    public FreeUI_ClearEditText etLotId;
    @BindView(R.id.etUser)
    FreeUI_ClearEditText etUser;
    @BindView(R.id.tvLotTitle)
    TextView tvLotTitle;
    @BindView(R.id.tabLayout)
    CommonTabLayout tabLayout;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.rbSmallBox)
    RadioButton rbSmallBox;
    @BindView(R.id.rbBox)
    RadioButton rbBox;
    @BindView(R.id.rbJuan)
    RadioButton rbJuan;

    private AlreadyDoneFragment alreadyDoneFragment;
    private NotDoneFragment notDoneFragment;
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    public boolean isBoxPackageType = false;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pack_package;
    }

    @Override
    protected void initView() {
        notDoneFragment = new NotDoneFragment();
        mFragments.add(notDoneFragment);
        alreadyDoneFragment = new AlreadyDoneFragment();
        mFragments.add(alreadyDoneFragment);
        mTabEntities.add(new FreeUI_TabEntity("未包装",
                null, null));
        mTabEntities.add(new FreeUI_TabEntity("已包装",
                null, null));
        tabLayout.setTabData(mTabEntities, this, R.id.content, mFragments);
    }

    @Override
    protected void initData() {

        freeUI_titleView.setRightListener("校验", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!packType.equals("BoxPackageType")){
                    return;
                }

                JSONObject jsonObject = new JSONObject();
                JSONObject jsonObject1 = new JSONObject();
                try {
                    jsonObject1.put("PACKAGETYPE", "BoxPackageType");
                    JSONArray jsonArray = new JSONArray(new Gson().toJson(notDoneFragment.packListAdapter.getData()));
                    jsonObject1.put("LOTLIST", jsonArray);
                    jsonObject.put("Data",jsonObject1);
                    jsonObject.put("MessageName","EUIT.EUITPACKINGCHECK");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                NetUtils.requestPostMesForwardUtils(jsonObject, this,new FreeUI_DialogEntityCallBack<ResponseBean<BoxPackageTypeEntity>>(
                        new TypeToken<ResponseBean<BoxPackageTypeEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {
                    @Override
                    public void onSuccess(Response<ResponseBean<BoxPackageTypeEntity>> response) {
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            showToast("校验成功",true);
                            isBoxPackageType = true;
                            ArrayList<PackBean> lotlist = response.body().getBody().getLOTLIST();
                            if (lotlist.size() > 0){
                                for (PackBean lotBean : lotlist) {
                                    notDoneFragment.addData(lotBean);
                                }
                                euitprint(lotlist);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<ResponseBean<BoxPackageTypeEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "BoxPackageType");
                    }
                });
            }
        });

        etLotId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(final CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    boolean isHave = false;
                    for (PackBean entity : notDoneFragment.packListAdapter.getData()) {
                        if (entity.getLOTID().equalsIgnoreCase(s.toString())) {
                            isHave = true;
                            break;
                        }
                    }
                    if (isHave) {
                        showToast("批次号已存在列表中", false);
                    } else {
                        String userName = etUser.getText().toString();
                        if (userName.isEmpty()){
                            showToast("请输入操作人工号",false);
                            return;
                        }
                        requestUser(userName, new CallBack() {
                            @Override
                            public void success() {
                                requestLotData(s.toString());
                            }

                            @Override
                            public void fail() {
                                showToast("操作人工号验证失败，请重新输入", false);
                            }

                            @Override
                            public void error() {
                                showToast("连接不到服务器，请重试", false);
                            }
                        });
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void euitprint(ArrayList<PackBean> lotlist) {
        JSONObject jsonObject2 = new JSONObject();
        try {
            jsonObject2.put("PACKAGETYPE", "BOX");
            JSONArray jsonArray = new JSONArray(new Gson().toJson(lotlist));
            jsonObject2.put("LOTLIST", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestWithNormalCallBack("EUIT.EUITPRINT", jsonObject2, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>(
                new TypeToken<BaseResponseBean<?>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<?>> response) {
                if (response.body().isSuccess(PackPackageActivity.this, false)) {
                    showToast("打印成功", true);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<?>> response) {
                super.onError(response);
                loadError(response.getException(), "打印请求");
            }
        });
    }

    private void requestLotData(String lotId) {
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject1.put("LOTID", lotId);
            jsonObject1.put("ACTIONTYPE", packType.equals("ReelPack") ? "CHECKPACKREELINFO" : "CHECKPACKLOTINFO");
            jsonObject1.put("PACKAGETYPE", packType);
            JSONArray jsonArray = new JSONArray(new Gson().toJson(notDoneFragment.packListAdapter.getData()));
            jsonObject1.put("LOTLIST", jsonArray);
            jsonObject.put("Data",jsonObject1);
            jsonObject.put("MessageName","EUIT.EUITLOTQUERY");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject,this, new FreeUI_DialogEntityCallBack<ResponseBean<ResponseQueryBean>>(
                new TypeToken<ResponseBean<ResponseQueryBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<ResponseQueryBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    PackBean packBean = response.body().getBody().getLOT();
                    notDoneFragment.addData(packBean);
                    etLotId.requestFocus();
                    etLotId.setText("");
                }
            }

            @Override
            public void onError(Response<ResponseBean<ResponseQueryBean>> response) {
                super.onError(response);
                loadError(response.getException(), "包装LOT请求");
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("包装");
        return new FreeUI_AddViewEntity("header", llMain);
    }

    public void setAlreadyDoneList(List<PackBean> list) {
        alreadyDoneFragment.packListAdapter.addData(0, list);
    }

    public void setNotDoneList(List<PackBean> list) {
        for (PackBean obj : list) {
            for (PackBean packBean : notDoneFragment.packListAdapter.getData()) {
                if (packBean.getLOTID().equals(obj.getLOTID())) {
                    packBean.setMAINQTY(obj.getMAINQTY());
                }
            }
        }
        notDoneFragment.packListAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.rbSmallBox, R.id.rbBox, R.id.rbJuan})
    public void onViewClicked(View view) {
        boolean isOk = true;
        if (notDoneFragment.packListAdapter.getData().size() > 0 || alreadyDoneFragment.packListAdapter.getData().size() > 0) {
            isOk = false;
            showToast("列表中存在批次信息，不能更换", false);
        }
        switch (view.getId()) {
            case R.id.rbSmallBox:
                if (isOk) {
                    packType = "SmallBoxPackageType";
                } else {
                    setCheck();
                }
                break;
            case R.id.rbBox:
                if (isOk) {
                    packType = "BoxPackageType";
                } else {
                    setCheck();
                }
                break;
            case R.id.rbJuan:
                if (isOk) {
                    packType = "ReelPack";
                } else {
                    setCheck();
                }
                break;
        }
    }

    private void setCheck() {
        switch (packType) {
            case "SmallBoxPackageType":
                rbSmallBox.setChecked(true);
                break;
            case "BoxPackageType":
                rbBox.setChecked(true);
                break;
            case "ReelPack":
                rbJuan.setChecked(true);
                break;
        }
    }
}
